//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.yaukie.base.aspect;

import com.github.pagehelper.PageHelper;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.yaukie.base.annotation.EnablePage;

@Component
@Aspect
public class PageAop {
    private static final Logger log = LoggerFactory.getLogger(PageAop.class);

    public PageAop() {
    }

    @Around("org.yaukie.base.arch.Architecture.pagePointCut()")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        EnablePage enablePage = (EnablePage)method.getAnnotation(EnablePage.class);
        if (StringUtils.isEmpty(enablePage)) {
            Object obj = joinPoint.proceed();
            log.info("当前方法不支持分页查询,方法名称为:{}", method.getName());
            return obj;
        } else {
            String[] parameters = methodSignature.getParameterNames();
            if (parameters.length < 2) {
                Object obj = joinPoint.proceed();
                log.info("分页参数必须要包含limit与offset:{}", method.getName());
                return obj;
            } else {
                int offset = 0;
                int limit = 10;
                Object[] args = joinPoint.getArgs();

                for(int i = 0; i < parameters.length; ++i) {
                    String paramName = parameters[i];
                    if (paramName.equals("offset")) {
                        offset = Integer.parseInt(args[i] + "");
                    }

                    if (paramName.equals("limit")) {
                        limit = Integer.parseInt(args[i] + "");
                    }
                }

                Object proceed;
                if (offset == 0 && limit == 0) {
                    proceed = joinPoint.proceed();
                    return proceed;
                } else {
                    log.info("拦截到分页请求,当前页码:{},每页{}条数据==>", offset, limit);
                    PageHelper.offsetPage(offset, limit);
                    log.info("分页请求结束==>");
                    proceed = joinPoint.proceed();
                    return proceed;
                }
            }
        }
    }
}
